package com.sunshine.wrongquestionset.activity.exercise_history

import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.Spinner
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.components.Description
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import com.google.android.material.button.MaterialButton
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.activity.add_question.SpinnerAdapter
import com.sunshine.wrongquestionset.activity.base.BaseActivity
import com.sunshine.wrongquestionset.callback.OnRefreshListener
import com.sunshine.wrongquestionset.room.entity.*
import kotlinx.android.synthetic.main.activity_exercise_history.*
import kotlinx.android.synthetic.main.activity_exercise_history.pieChart
import kotlinx.android.synthetic.main.fragment_analyzer.*
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class ExerciseHistoryActivity : BaseActivity() {

    private lateinit var viewModel: ExerciseHistoryViewModel
    //错题集，默认-1 表示全部
    private var questionSetId = -1
    //科目，默认-1 表示全部
    private var subjectId = -1

    //筛选的开始和结束时间
    private var startTime: Long = 0L
    private var endTime: Long = Date().time

    private lateinit var adapter: ExerciseHistoryRecyclerAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_exercise_history)
        setTitle(getString(R.string.label_exercise_history))

        viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(application)).get(ExerciseHistoryViewModel::class.java)

        recyclerView.setLayoutManager(LinearLayoutManager(this))
        adapter = ExerciseHistoryRecyclerAdapter(null)
        recyclerView.setAdapter(adapter)
        toQuery()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_exercise_history, menu)
        return super.onCreateOptionsMenu(menu)
    }

    @SuppressLint("SimpleDateFormat")
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.query -> {
                val builder = MaterialAlertDialogBuilder(this)
                builder.apply {
                    setTitle(getString(R.string.query_title))
                    val view = LayoutInflater.from(this@ExerciseHistoryActivity).inflate(R.layout.view_query_exercise_history, null, false)
                    val subjectSpinner: View = view.findViewById(R.id.include_question_subject)
                    val setSpinner: View = view.findViewById(R.id.include_question_set)
                    val startTimeButton: MaterialButton = view.findViewById(R.id.button_start_time)
                    val endTimeButton: MaterialButton = view.findViewById(R.id.button_end_time)

                    val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd")

                    initQuestionSubjectSpinner(subjectSpinner, setSpinner)
                    initQuestionSetSpinner(setSpinner)

                    startTimeButton.setOnClickListener {
                        val datePickerDialog = DatePickerDialog(this@ExerciseHistoryActivity)
                        datePickerDialog.setOnDateSetListener { view, year, month, dayOfMonth ->
                            val calendar: Calendar = Calendar.getInstance()
                            calendar.set(year, month, dayOfMonth)
                            startTime = calendar.timeInMillis
                            startTimeButton.text = simpleDateFormat.format(calendar.time)
                        }
                        datePickerDialog.show()
                    }
                    endTimeButton.setOnClickListener {
                        val datePickerDialog = DatePickerDialog(this@ExerciseHistoryActivity)
                        datePickerDialog.setOnDateSetListener { view, year, month, dayOfMonth ->
                            val calendar: Calendar = Calendar.getInstance()
                            calendar.set(year, month, dayOfMonth)
                            endTime = calendar.timeInMillis
                            endTimeButton.text = simpleDateFormat.format(calendar.time)
                        }
                        datePickerDialog.show()
                    }

                    setView(view)

                    setPositiveButton("确定") {_, _ ->
                        toQuery()
                    }
                }
                builder.create().show()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    /**
     * 按照条件筛选哪个集合中的错题
     */
    private fun toQuery() {
        getLoginUserId(object : OnRefreshListener<String>() {
            override fun onUpdate(obj: String) {
                super.onUpdate(obj)

                viewModel.getWrongQuestionInDate(subjectId, questionSetId, startTime, endTime).observe(this@ExerciseHistoryActivity, Observer {
                    toQueryWrongQuestion(it)
                })

//                //筛选科目
//                if (subjectId != -1) {
//                    //筛选错题集
//                    if (questionSetId != -1) {
//                        viewModel.getQuestionInSet(questionSetId).observe(this@ExerciseHistoryActivity, Observer {
//                            toQueryWrongQuestion(it)
//                        })
//                    }
//                    //该科目全部错题集
//                    else {
//                        viewModel.getQuestionInSubject(subjectId).observe(this@ExerciseHistoryActivity, Observer {
//                            toQueryWrongQuestion(it)
//                        })
//                    }
//
//                }
//                //全部科目
//                else {
//                    viewModel.getQuestion(obj).observe(this@ExerciseHistoryActivity, Observer {
//                        toQueryWrongQuestion(it)
//                    })
//                }
            }
        })

    }

    /**
     * 筛选错题
     */
    private fun toQueryWrongQuestion(wrongQuestionList: List<WrongQuestionBean>?) {
        //对空情况处理，让空仍然刷新
        if (wrongQuestionList.isNullOrEmpty()) {
            adapter.setFilter(null)
            textView_info.text = getString(R.string.no_exercise)
            pieChart.visibility = View.GONE
            return
        }

        adapter.setFilter(wrongQuestionList)
        calculateScore(wrongQuestionList)

//        val wrongQuestionList = ArrayList<WrongQuestionEntity>()
//        questionList.forEach {
//            viewModel.getExerciseHistoryInDateAndQuestionId(it.id, startTime, endTime).observe(this, Observer {wrongQuestionListOnce ->
//                wrongQuestionListOnce?.forEach {wrongQuestionEntity ->
//                    wrongQuestionList.add(wrongQuestionEntity)
//                    adapter.setFilter(wrongQuestionList)
//                    calculateScore(wrongQuestionList)
//                }
//            })
//        }
    }

    @SuppressLint("SetTextI18n")
    private fun calculateScore(wrongQuestionList: List<WrongQuestionBean>) {
        var score = 0.0f
        var totalScore = 0.0f
        wrongQuestionList.forEach {
            score += it.score
            totalScore += it.totalScore
        }

        textView_info.text = "$score/$totalScore"

        val list = ArrayList<PieEntry>()
        list.add(PieEntry(score, "得分"))
        list.add(PieEntry(totalScore - score, "失分"))
        val pieDataSet = PieDataSet(list, "总得分占比")
        val pieData = PieData(pieDataSet)
        pieChart.data = pieData
        val description = Description()
        description.text = "得分占比饼状图"
        pieChart.description = description
        pieDataSet.setColors(getColor(R.color.chart_color_2), getColor(R.color.chart_color_1)) //设置各个数据的颜色

        pieChart.animateY(1000, Easing.EaseInOutQuad)
        pieChart.setHoleColor(Color.TRANSPARENT)

        pieChart.invalidate()
    }

    /**
     * 初始化题目科目的下拉选择
     */
    private fun initQuestionSubjectSpinner(subjectView: View, setView: View) {
        viewModel.getQuestionSubject(getLoginUserId()).observe(this, Observer {subjectList ->
            val spinnerText: TextView = subjectView.findViewById(R.id.textView_spinner)
            val spinner: Spinner = subjectView.findViewById(R.id.spinner)

            //添加全部选项
            val subjectMutableList = mutableListOf<SubjectEntity>()
            subjectMutableList.add(SubjectEntity(-1, getLoginUserId(), "全部"))
            subjectList?.forEach {
                subjectMutableList.add(it)
            }

            spinnerText.text = getString(R.string.question_subject)
            spinner.adapter = SpinnerAdapter(
                this,
                R.layout.view_spinner_item,
                R.id.textView_spinner_item,
                subjectMutableList,
                SpinnerAdapter.TYPE_SUBJECT
            )
            spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onNothingSelected(parent: AdapterView<*>?) {

                }

                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                    //切换后更新科目id
                    subjectId = id.toInt()
                    //刷新该科目的错题集
                    initQuestionSetSpinner(setView)
                }
            }
        })
    }

    /**
     * 初始化题目错题集的下拉选择
     */
    private fun initQuestionSetSpinner(setView: View) {
        viewModel.getQuestionSet(getLoginUserId(), subjectId).observe(this, Observer {questionSetList ->

            val questionSetMutableList = mutableListOf<QuestionSetEntity>()
            questionSetMutableList.add(QuestionSetEntity(-1, getLoginUserId(), "全部", null, -1, ""))
            questionSetList?.forEach {
                questionSetMutableList.add(it)
            }
//            //如果当前科目没有错题集，则用-1标记
//            if(it.isNullOrEmpty()) questionSetId = -1

            val spinnerText: TextView = setView.findViewById(R.id.textView_spinner)
            val spinner: Spinner = setView.findViewById(R.id.spinner)

            spinnerText.text = getString(R.string.question_set)
            spinner.adapter = SpinnerAdapter(
                this,
                R.layout.view_spinner_item,
                R.id.textView_spinner_item,
                questionSetMutableList,
                SpinnerAdapter.TYPE_QUESTION_SET
            )
            spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onNothingSelected(parent: AdapterView<*>?) {

                }

                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                    //切换后更新错题集id
                    questionSetId = id.toInt()
                }
            }
        })
    }
}